package com.example.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@WebFilter(filterName = "commonFilter", urlPatterns = "/*")
public class CommonFilter implements Filter {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private Map<Object, Object> count;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("init方法执行了");
        count = (Map<Object, Object>) filterConfig.getServletContext().getAttribute("count");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        logger.info("doFilter方法执行了");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        if (count.containsKey(
                servletRequest.getRemoteAddr())) {
            List<StringBuffer> user_urls =
                    (ArrayList) count.get(servletRequest.getRemoteAddr());
            user_urls.add(request.getRequestURL());
            count.put(servletRequest.getRemoteAddr(), user_urls);
        } else {
            List<StringBuffer> user_urls = new ArrayList<>();
            user_urls.add(request.getRequestURL());
            count.put(servletRequest.getRemoteAddr(), user_urls);
        }
        logger.info("访问人数:" + count.entrySet().size());
    }

    @Override
    public void destroy() {
        logger.info("destroy方法执行了");
    }
}